var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen('8001');
console.log('running 8001');

function handler (req, res) {
  fs.readFile(__dirname + '../admin/index.php',
  function (err, data) {
    if (err){
      res.writeHead(500);
      return res.end('Error loading index'); }
    res.writeHead(200);
    res.end(data);
  });
}

var usernames = {};
var rooms = ['Room chat'];
var ids={};

io.sockets.on('connection', function (socket) 
{
		socket.on('sendchat', function (data) 
		{
			io.sockets.emit('updatechat', socket.username, socket.id, data);
			process.on('connection', function (err) 
			{
				console.log('lang nghe connection: ' + err);
			});
	});
	

	// khi client phát ra "su kien adduser ', hàm này thực thi
	socket.on('adduser', function (username,domain,id)
	{
		socket.username = username;
		usernames[username] = username;
		socket.room =domain;
		socket.join(domain);
		socket.emit('updatechat', 'Thông báo', 'Bạn đã kết nối');
		console.log(domain);
		socket.broadcast.to(domain).emit('updatechat', 'Thông báo', username + ' đã kết nối vào phòng chat');
		io.sockets.emit('updateusers', username);
		io.sockets.emit('updaterooms', rooms, domain);
	});

//****************moi update*******************/
	socket.on('create', function(room) {
        rooms.push(room);
        socket.emit('updaterooms', rooms, socket.room);
    });

	//private message
	/*socket.on('privatemessage', function (from, msg) {
	    console.log('I received a private message by ', from, ' saying ', msg);
	  });*/

	//SwitchRoom
	socket.on('switchRoom', function(newroom) {
        var oldroom;
        oldroom = socket.room;
        socket.leave(socket.room);
        socket.join(newroom);
        socket.emit('updatechat', 'Thông báo: ', 'Bạn đã tham gia phòng chat ' + newroom);
        socket.broadcast.to(oldroom).emit('updatechat', 'Thông báo: ', socket.username + ' Rời khỏi phòng chat');
        socket.room = newroom;
        socket.broadcast.to(newroom).emit('updatechat', 'Thông báo: ', socket.username + ' Tham gia vào phòng chat');
        socket.emit('updaterooms', rooms, newroom);
    });
//****************End update*******************/

	// khi client thoat thi ham hay thuc thi
	socket.on('disconnect', function()
	{
		delete usernames[socket.username];
		delete usernames[socket.id];
		socket.broadcast.emit('updatechat', 'Thông báo', socket.username + ' đã thoát');
		socket.leave(socket.room);
	});
})
